//
//  MemberListController.m
//  MyChatDemo
//
//  Created by DragonYao on 2017/9/11.
//  Copyright © 2017年 DragonYao. All rights reserved.
//

#import "MemberListController.h"
#import "MyChatFriendListCell.h"
#import "AddFriendViewController.h"
#import "ChatViewController.h"

static NSString *kListCellId = @"MyChatFriendListCell";

@interface MemberListController ()<UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate> {
    NSFetchedResultsController *_fetchResultVC;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSArray<XMPPUserCoreDataStorageObject *> *myFriends;

@end

@implementation MemberListController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"通讯录";
//    UIBarButtonItem *rightBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"add"] style:UIBarButtonItemStylePlain target:self action:@selector(showAddFriendView:)];
//    rightBtnItem.tintColor = [UIColor blackColor];
//    self.navigationItem.rightBarButtonItem = rightBtnItem;
    
    [self loadMyFriends2];
    [self setupTabelView];
}

- (void)setupTabelView {
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([MyChatFriendListCell class]) bundle:nil] forCellReuseIdentifier:kListCellId];
}


/**
 *  这种方法获取好友，存在缺陷【如：如果删除了好友 或者 添加了好友 列表不会更新】
 */
- (void)loadMyFriends1 {
    //1、访问coredata的上下文
    NSManagedObjectContext *context = [XMPPManager sharedManager].rosterStorage.mainThreadManagedObjectContext;
    //2、【NSFetchRequest】要访问那张表
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"XMPPUserCoreDataStorageObject"];
    //3.1过滤掉本身的ID
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"streamBareJidStr = %@", [UserLocalInfo sharedUserInfo].myJid];
    request.predicate = predicate;
    //3.2排序
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"nickname" ascending:YES];
    request.sortDescriptors = @[sort];
    //4、请求好友列表
    NSError *error = nil;
    self.myFriends = [context executeFetchRequest:request error:&error];
    if (error) {
        SLog(@"Fetch friends error : %@", error);
    }
    
    SLog(@"My Friends %@", self.myFriends);
}

/**
 *  方法二：使用FetchResultController获取更新【因为当删除或者添加好友的时候回调代理方法】
 *  只要有内容更新，就会回调代理方法
 *  XMPPUserCoreDataStorageObject 中的属性sectionNum 0:在线 1:离开 2:离线
 */

- (void)loadMyFriends2 {
    //1、访问coredata的上下文
    NSManagedObjectContext *context = [XMPPManager sharedManager].rosterStorage.mainThreadManagedObjectContext;
    //2、【NSFetchRequest】要访问那张表
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"XMPPUserCoreDataStorageObject"];
    //3.1过滤掉本身的ID
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"streamBareJidStr = %@", [UserLocalInfo sharedUserInfo].myJid];
    request.predicate = predicate;
    //3.2排序
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"nickname" ascending:YES];
    request.sortDescriptors = @[sort];
    //4、请求好友列表
    _fetchResultVC = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
    _fetchResultVC.delegate = self;
    //开始执行查询
    NSError *error = nil;
    [_fetchResultVC performFetch:&error];
    if (error) {
        SLog(@"Fetch friends error : %@", error);
    }
//    SLog(@"My Friends %@", self.myFriends);
}

#pragma mark - TableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    return self.myFriends.count;
    return _fetchResultVC.fetchedObjects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyChatFriendListCell *cell = [tableView dequeueReusableCellWithIdentifier:kListCellId];
//    XMPPUserCoreDataStorageObject *friend = self.myFriends[indexPath.row];
    XMPPUserCoreDataStorageObject *friend = _fetchResultVC.fetchedObjects[indexPath.row];
    SLog(@"photo == %@", friend.photo);
    cell.headImgView.image = friend.photo == nil ? [UIImage imageNamed:@"avertor"] : friend.photo;
    cell.nickNameLabel.text = [NSString stringWithFormat:@"%@", friend.nickname];
    switch ([friend.sectionNum integerValue]) {
        case 0:
           cell.lastMessageLabel.text = @"在线";
            break;
        case 1:
            cell.lastMessageLabel.text = @"离开";
            break;
        case 2:
            cell.lastMessageLabel.text = @"离线";
            break;
        default:
            break;
    }
    return cell;
}

#pragma mark - TableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 64.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ChatViewController *chatVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:NSStringFromClass([ChatViewController class])];
    XMPPUserCoreDataStorageObject *friend = _fetchResultVC.fetchedObjects[indexPath.row];
    chatVC.friendJID = friend.jid;
    [self.navigationController showViewController:chatVC sender:nil];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    XMPPUserCoreDataStorageObject *friend = _fetchResultVC.fetchedObjects[indexPath.row];
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除好友" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [[XMPPManager sharedManager].roster removeUser:friend.jid];
    }];
    return @[deleteAction];
}

#pragma mark - NSFetchedResultsControllerDelegate
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    SLog(@"数据发生改变");
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)showAddFriendView:(id)sender {
    AddFriendViewController *addVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:NSStringFromClass([AddFriendViewController class])];
    addVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:addVC animated:YES];
}

@end
